﻿using System;
using System.Reflection;

namespace Batik.Web.UI.Controls
{
    // Custom ControlBuilder that instantiates the generic control when the page
    // is constructed.
    internal class TextBoxControlBuilder : System.Web.UI.ControlBuilder
    {
        public override void Init(System.Web.UI.TemplateParser parser, System.Web.UI.ControlBuilder parentBuilder, Type type, string tagName, string id, System.Collections.IDictionary attribs)
        {
            Type newType = type;
            if (attribs.Contains("datatype"))
            {
                // If objecttype is specified, create a generic type that is bound to that
                // argument and then hide the objecttype attribute.
                Type genericType = typeof(TextBox<>);
                string newTypeName = (string)attribs["datatype"];
                Type typeAttr = typeof(DataType);
                MemberInfo[] memberInfo = typeAttr.GetMember(newTypeName);
                if (memberInfo != null && memberInfo.Length > 0)
                {
                    object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DataTypeAttribute), false);
                    if (attrs != null && attrs.Length > 0)
                    {
                        newTypeName = ((DataTypeAttribute)attrs[0]).Text;
                    }
                }
                Type genericArg = Type.GetType(newTypeName, true, true);
                //Type genericArg = Type.GetType((string)attribs["datatype"], true, true);
                newType = genericType.MakeGenericType(genericArg);
                attribs.Remove("datatype");

            }
            base.Init(parser, parentBuilder, newType, tagName, id, attribs);
        }
    }
}
